class Item(object):

    def __init__(self):
        self.tag = ""
        self.data = ""
        self.parent = 0
        self.subs = []
        self.attrs = []

    def GetItem(self, index, tag):
        cnt = 1
        nullItem = Item()
        for subitem in self.subs:
            if subitem.tag == tag:
                if cnt == index:
                    return subitem
                else:
                    cnt = cnt + 1
        return nullItem

    def GetAttr(self, attr):
        re = ""
        for attrib in self.attrs:
            if attrib[0] == attr:
                return attrib[1]
        return re

    def FindItems(self, tag, attrs):
        re = []
        # print(self.tag)
        if tag == self.tag:
            found = 1
            # print(self.attrs)
            for attr in attrs:
                if len(attr) == 1 and len(self.attrs) >= 1:
                    if attr[0] not in self.attrs[0]:
                        found = 0
                        break
                elif attr not in self.attrs:
                    found = 0
                    break
            if found == 1:
                re.append(self)
        for subitem in self.subs:
            re = re + subitem.FindItems(tag, attrs)
        return re

from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):

    def __init__(self):
        HTMLParser.__init__(self)
        self.item = Item()
        self.curItem = self.item
    
    def handle_starttag(self, tag, attrs):
        newItem = Item()
        newItem.tag = tag
        newItem.attrs = attrs
        newItem.parent = self.curItem
        newItem.subs = []
        self.curItem.subs.append(newItem)
        self.curItem = newItem
        
    def handle_endtag(self, tag):        
        self.curItem = self.curItem.parent
 
    def handle_data(self, data):
        self.curItem.data = data

    def FindItems(self, tag, attrs):
        return self.item.FindItems(tag, attrs)
      
if __name__ == '__main__':
    f = open("D:\\Dagou\\test.htm",'r')
    
    parser = MyHTMLParser(strict=False)
    parser.feed(f.read())
    #parser.feed('<html><head><title>Test</title></head>'
    #            '<body><h1>Parse me!</h1></body></html>')
    Myattrs = [('class','item-box')]
    #attrs = []
    result = parser.FindItems("div",Myattrs)
    for item in result:
        Myattrs = [('class','col price')]
        res = item.FindItems("div",Myattrs)
        for price in res:
            print(price.data)
    f.close()
